﻿using CommonLib;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAppConsumer;

/// <summary>
/// 测试Fanout模式
/// </summary>
internal class TestFanoutPattern
{
    private static readonly string ExchangeName="logs";

    /// <summary>
    /// Fanout 发布订阅模式
    /// </summary>
    public static void TestFanout()
    {
        // 1 创建信道 channel
        var channel = RabbitMQUtil.CreateChannel();

        // 2 声明交换机
        channel.ExchangeDeclare(ExchangeName, type: "fanout");

        // 3 声明队列
        var queueName = "fanout-Queue1";
        channel.QueueDeclare(queueName, true, false, false, null);

        // 4 绑定队列到交换机
        channel.QueueBind(queueName, ExchangeName, "");

        // 5 读取消息的回调
        var consumer = new AsyncEventingBasicConsumer(channel);
        consumer.Received += ComsumerMessage;
        async Task ComsumerMessage(object sender, BasicDeliverEventArgs args)
        {
            try
            {
                var bytes = args.Body.ToArray();
                var msg = Encoding.UTF8.GetString(bytes);
                Console.WriteLine("Consumer1 收到了消息：" + msg);
                channel.BasicAck(args.DeliveryTag, multiple: false);
                await Task.Delay(1000);
            }
            catch (Exception ex)
            {
                channel.BasicReject(args.DeliveryTag, true);
                Console.WriteLine("处理消息异常：" + ex.Message);
            }
        }

        // 6 发布消息
        channel.BasicConsume(queueName, autoAck: false, consumer: consumer);
        Console.ReadLine();

    }


}
